package com.changgou.order.task;

import com.changgou.order.pojo.OrderLog;
import com.changgou.order.service.OrderService;
import com.changgou.pay.feign.WeixinPayFeign;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author ：hushengjin
 */

@Component
public class QueryPayStatus {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WeixinPayFeign weixinPayFeign;
    @Autowired
    private OrderService orderService;


    @Scheduled(cron = "0/5 * * * * ?")
    public void queryPay() {
        Object logId = redisTemplate.boundListOps("OrderLogList").rightPop();
        if (logId != null) {
            //查询日志信息
            OrderLog orderLog = (OrderLog) redisTemplate.boundHashOps("OrderLog").get(logId);
            if (orderLog == null) {
                //如果没有日志，说明已经支付完成或者已经操作了
                return;
            }
            Result result = weixinPayFeign.queryStatus(orderLog.getId());
            Map<String, String> resultMap = (Map<String, String>) result.getData();
            //网络通信标识
            String returnCode = resultMap.get("return_code");
            //业务返回代码
            String resultCode = resultMap.get("result_code");
            //交易状态
            String tradeState = resultMap.get("trade_state");
            if (returnCode.equalsIgnoreCase("SUCCESS") && resultCode.equalsIgnoreCase("SUCCESS")) {
                if (tradeState.equalsIgnoreCase("SUCCESS")) {
                    //支付成功,修改订单
                    orderService.updateStatus(orderLog.getOrderId(), resultMap.get("transaction_id"), orderLog);
                } else if (tradeState.equalsIgnoreCase("notpay") || tradeState.equalsIgnoreCase("userpaying")) {
                    //未支付或者正在支付，则将用户的支付信息存入到队列，后面再次调用查询状态
                    redisTemplate.boundListOps("OrderLogList").leftPush(logId.toString());
                } else {
                    //取消本地订单状态,回滚库存，refund:转入退款       closed：已关闭       revoked：已撤销     payerror:支付失败
                    orderService.deleteOrder(orderLog);
                }
            }
        }
    }

}
